package com.youmeek.demo.web.servlet.servlet;

import com.youmeek.demo.web.servlet.service.Impl.UserServiceImpl;
import com.youmeek.demo.web.servlet.service.UserService;
import net.sf.json.JSONArray;

import javax.jws.WebService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "getQiyeWeixinUserInfoServlet", urlPatterns = {"/profileUrl"}, loadOnStartup = 2)
public class GetQiyeWeixinUserInfoServlet extends HttpServlet {

	public GetQiyeWeixinUserInfoServlet() {

	}

	@Override
	public void init() throws ServletException {
		super.init();
	}

	@Override
	protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html; charset=utf-8");
		String action = req.getParameter("action");
		if (action.equals("ajax_login")){
			formLogin(req,resp);
		}else if (action.equals("form_login")){
			ajaxLogin(req,resp);
		}


	}

	private static void formLogin(final HttpServletRequest req, final HttpServletResponse resp){
		try {
			String username = req.getParameter("userName");
			String password = req.getParameter("passWord");
			if (UserServiceImpl.getInstance().loginUser(username,password)){
				resp.sendRedirect("index.jsp");
			}else{
				resp.sendRedirect("login.jsp");
			}
		}catch (Exception e){
			System.err.println(e.getMessage());
		}
	}

	private static void ajaxLogin(final HttpServletRequest req, final HttpServletResponse resp){
		try {
			Map<String,Boolean> map = new HashMap<>();
			String username = req.getParameter("userName");
			String password = req.getParameter("passWord");
			if (UserServiceImpl.getInstance().loginUser(username,password)){
				map.put("data",true);
				req.getRequestDispatcher("index.jsp").forward(req,resp);
			}else{
				map.put("data",false);
				resp.sendRedirect("login.jsp");
			}
			JSONArray json = JSONArray.fromObject(map);
			resp.getWriter().print(json);
		}catch (Exception e){
			System.err.println(e.getMessage());
		}
	}



}

